import { useState, useEffect } from 'react'
import type { ElectronAPI } from './interfaces'
import type { IAppService, IApiService, IElectronService } from './interfaces'
import type {
  HttpRequestConfig,
  HttpResponse
} from './interfaces'

/**
 * 全局 electronAPI 实例
 */
export const electronAPI: ElectronAPI = window.electronAPI

// 声明全局 Window 类型
declare global {
  interface Window {
    electronAPI: ElectronAPI
  }
}

// ==================== 类型定义 ====================

export interface CrawlProgress {
  profileId: string
  current: number
  total: number
  status: 'running' | 'completed' | 'error' | 'crawling'
  message?: string
  crawledVideos?: number
  totalVideos?: number
}

export interface HomePageConfig {
  id: string
  name: string
  url: string
  platform: string
  createdAt: string
  updatedAt: string

  // 抖音主页信息字段
  author?: string
  followCount?: number
  fansCount?: number
  likesReceived?: number
  likesGiven?: number
  worksCount?: number
  lastWorkTime?: string
  extractedWorksCount?: number
  localVideoCount?: number
  localImageTextCount?: number
  localLikedCount?: number
  remark?: string
  addTime?: string
}

export interface VideoInfo {
  id: string
  title: string
  url: string
  thumbnail: string
  duration: number
  uploadTime: string
  viewCount: number
  likeCount: number
  commentCount: number
  shareCount: number
}

export interface CrawlResult {
  videos: VideoInfo[]
  profileInfo: any
  error?: string
}

export interface DownloadProgress {
  id: string
  videoId: string
  progress: number
  status: 'downloading' | 'completed' | 'failed'
  error?: string
}

export interface User {
  id: string
  phone: string
  username?: string
  nickname?: string
  avatar?: string
  email?: string
}

export interface AuthState {
  isLoggedIn: boolean
  user: User | null
}

export const SMS_CODE_TYPE = {
  LOGIN: 1,    // 登录验证码
  REGISTER: 2, // 注册验证码
  RESET: 3     // 重置密码验证码
} as const

export type SmsCodeType = typeof SMS_CODE_TYPE[keyof typeof SMS_CODE_TYPE]

// ==================== 认证服务 ====================

class AuthService {
  private static instance: AuthService
  private authState: AuthState = {
    isLoggedIn: false,
    user: null
  }
  private listeners: ((state: AuthState) => void)[] = []
  private accessToken: string | null = null

  static getInstance(): AuthService {
    if (!AuthService.instance) {
      AuthService.instance = new AuthService()
    }
    return AuthService.instance
  }

  // 订阅认证状态变化
  subscribe(listener: (state: AuthState) => void): () => void {
    this.listeners.push(listener)
    return () => {
      this.listeners = this.listeners.filter(l => l !== listener)
    }
  }

  // 通知所有监听器
  private notifyListeners() {
    this.listeners.forEach(listener => listener(this.authState))
  }

  // 设置认证状态
  private setAuthState(newState: Partial<AuthState>) {
    this.authState = { ...this.authState, ...newState }
    this.notifyListeners()
  }

  // 保存 Token
  private saveTokens(accessToken: string, refreshToken: string) {
    this.accessToken = accessToken
    localStorage.setItem('access_token', accessToken)
    localStorage.setItem('refresh_token', refreshToken)

    // 设置主进程的认证令牌
    appService.setAuthToken(accessToken)
  }

  // 清除 Token
  private clearTokens() {
    this.accessToken = null
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')

    // 清除主进程的认证令牌
    appService.setAuthToken(null)
  }

  // 获取 Access Token
  private getAccessToken(): string | null {
    if (!this.accessToken) {
      this.accessToken = localStorage.getItem('access_token')
    }
    return this.accessToken
  }

  // 发送验证码
  async sendVerificationCode(phone: string, codeType: 'login' | 'register'): Promise<{ success: boolean; message?: string }> {
    try {
      const typeMap = {
        login: SMS_CODE_TYPE.LOGIN,
        register: SMS_CODE_TYPE.REGISTER
      }

      const result = await appService.sendCode(phone, typeMap[codeType])

      if (result) {
        return { success: true, message: "53d190016210529f" }
      }
      return { success: false, message: '发送验证码失败' }
    } catch (error) {
      console.error('Send verification code error:', error)

      let errorMessage = '网络错误，请稍后重试'
      if (error instanceof Error) {
        if (error.message.includes('ECONNREFUSED') || error.message.includes('无法连接到后端服务器')) {
          errorMessage = '无法连接到后端服务器，请确保后端服务正在运行'
        } else if (error.message.includes('ETIMEDOUT')) {
          errorMessage = '请求超时，请检查网络连接'
        } else {
          errorMessage = error.message || errorMessage
        }
      }

      return { success: false, message: errorMessage }
    }
  }

  // 验证码登录
  async loginWithCode(phone: string, code: string): Promise<{ success: boolean; message?: string }> {
    try {
      const result = await appService.loginWithCode(phone, code) as any

      if (result && result.data) {
        const responseData = result.data
        const tokenData = responseData.data || responseData

        // 保存 Token
        const accessToken = tokenData.access_token || tokenData.token
        const refreshToken = tokenData.refresh_token || tokenData.token
        this.saveTokens(accessToken, refreshToken)

        // 更新用户状态
        const userData = tokenData.user || responseData.user
        if (userData) {
          this.setAuthState({
            isLoggedIn: true,
            user: {
              id: userData.id?.toString() || userData.user_id?.toString() || '',
              phone: userData.phone || phone,
              nickname: userData.nickname || userData.name || '',
              avatar: userData.avatar || ''
            }
          })
        }

        console.log('Login with code success')
        return { success: true }
      } else {
        const errorMsg = '登录失败'
        console.log('Login with code failed:', errorMsg)
        return { success: false, message: errorMsg }
      }
    } catch (error) {
      console.error('Login with code error:', error)

      let errorMessage = '网络错误，请稍后重试'
      if (error instanceof Error) {
        if (error.message.includes('ECONNREFUSED') || error.message.includes('无法连接到后端服务器')) {
          errorMessage = '无法连接到后端服务器，请确保后端服务正在运行'
        } else if (error.message.includes('ETIMEDOUT')) {
          errorMessage = '请求超时，请检查网络连接'
        } else {
          errorMessage = error.message || errorMessage
        }
      }

      return { success: false, message: errorMessage }
    }
  }

  // 验证码注册
  async registerWithCode(phone: string, code: string): Promise<{ success: boolean; message?: string }> {
    try {
      const result = await appService.registerWithCode(phone, code) as any

      if (result && result.data) {
        const responseData = result.data
        const tokenData = responseData.data || responseData

        // 注册成功后，保存 Token 并自动登录
        const accessToken = tokenData.access_token || tokenData.token
        const refreshToken = tokenData.refresh_token || tokenData.token
        this.saveTokens(accessToken, refreshToken)

        // 更新用户状态
        const userData = tokenData.user || responseData.user
        if (userData) {
          this.setAuthState({
            isLoggedIn: true,
            user: {
              id: userData.id?.toString() || userData.user_id?.toString() || '',
              phone: userData.phone || phone,
              nickname: userData.nickname || userData.name || '',
              avatar: userData.avatar || ''
            }
          })
        }

        const successMsg = '注册成功'
        console.log('Register with code success:', successMsg)
        return { success: true, message: successMsg }
      } else {
        const errorMsg = '注册失败'
        console.log('Register with code failed:', errorMsg)
        return { success: false, message: errorMsg }
      }
    } catch (error) {
      console.error('Register with code error:', error)

      let errorMessage = '网络错误，请稍后重试'
      if (error instanceof Error) {
        if (error.message.includes('ECONNREFUSED') || error.message.includes('无法连接到后端服务器')) {
          errorMessage = '无法连接到后端服务器，请确保后端服务正在运行'
        } else if (error.message.includes('ETIMEDOUT')) {
          errorMessage = '请求超时，请检查网络连接'
        } else {
          errorMessage = error.message || errorMessage
        }
      }

      return { success: false, message: errorMessage }
    }
  }

  // 登录
  async login(phone: string, password: string): Promise<{ success: boolean; message?: string }> {
    try {
      const result = await appService.login(phone, password) as any

      if (result && result.data) {
        const responseData = result.data
        const tokenData = responseData.data || responseData

        // 保存 Token
        const accessToken = tokenData.access_token || tokenData.token
        const refreshToken = tokenData.refresh_token || tokenData.token
        this.saveTokens(accessToken, refreshToken)

        // 更新用户状态
        const userData = tokenData.user || responseData.user
        if (userData) {
          this.setAuthState({
            isLoggedIn: true,
            user: {
              id: userData.id?.toString() || userData.user_id?.toString() || '',
              phone: userData.phone || phone,
              nickname: userData.nickname || userData.name || '',
              avatar: userData.avatar || ''
            }
          })
        }
        return { success: true }
      } else {
        return { success: false, message: '登录失败' }
      }
    } catch (error) {
      return { success: false, message: '网络错误，请稍后重试' }
    }
  }

  // 注册
  async register(phone: string, password: string, name?: string): Promise<{ success: boolean; message?: string }> {
    try {
      const result = await appService.register(phone, password, name) as any

      if (result && result.data) {
        const responseData = result.data
        const tokenData = responseData.data || responseData

        // 保存 Token
        const accessToken = tokenData.access_token || tokenData.token
        const refreshToken = tokenData.refresh_token || tokenData.token
        this.saveTokens(accessToken, refreshToken)

        // 更新用户状态
        const userData = tokenData.user || responseData.user
        if (userData) {
          this.setAuthState({
            isLoggedIn: true,
            user: {
              id: userData.id?.toString() || userData.user_id?.toString() || '',
              phone: userData.phone || phone,
              nickname: userData.nickname || userData.name || name || '',
              avatar: userData.avatar || ''
            }
          })
        }
        return { success: true }
      } else {
        return { success: false, message: '注册失败' }
      }
    } catch (error) {
      return { success: false, message: '网络错误，请稍后重试' }
    }
  }

  // 登出
  async logout(): Promise<void> {
    try {
      // 这里可以调用后端的登出接口，但不需要等待响应
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      this.clearTokens()
      this.setAuthState({
        isLoggedIn: false,
        user: null
      })
    }
  }

  // 检查登录状态
  async checkAuthStatus(): Promise<void> {
    try {
      const token = this.getAccessToken()
      if (!token) {
        this.setAuthState({
          isLoggedIn: false,
          user: null
        })
        return
      }

      // 通过主进程检查用户状态
      const result = await appService.httpRequest({
        url: '/api/auth/user',
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      // 处理401错误（session过期）
      if (!result.success && result.status === 401) {
        this.clearTokens()
        this.setAuthState({
          isLoggedIn: false,
          user: null
        })
        return
      }

      if (result.success && result.data) {
        this.setAuthState({
          isLoggedIn: true,
          user: {
            id: result.data.user.id.toString(),
            phone: result.data.user.phone,
            username: result.data.user.username,
            nickname: result.data.user.nickname,
            avatar: result.data.user.avatar,
            email: result.data.user.email
          }
        })
      } else {
        this.clearTokens()
        this.setAuthState({
          isLoggedIn: false,
          user: null
        })
      }
    } catch (error) {
      console.error('Check auth status error:', error)
      this.clearTokens()
      this.setAuthState({
        isLoggedIn: false,
        user: null
      })
    }
  }

  // 获取当前认证状态
  getAuthState(): AuthState {
    return this.authState
  }
}

// ==================== 应用服务实现 ====================

/**
 * API服务实现类
 */
class ApiService implements IApiService {
  /**
   * 处理 HTTP API 响应并提取数据
   */
  private async handleHttpResponse<T = any>(apiCall: () => Promise<HttpResponse<T>>): Promise<T> {
    const response = await apiCall()
    if (response.success) {
      return response.data!
    } else {
      throw new Error(response.error?.message || '请求失败')
    }
  }

  // 认证相关 API
  async login(phone: string, password: string) {
    return this.handleHttpResponse(() => electronAPI.api.login(phone, password))
  }

  async register(phone: string, password: string, name?: string) {
    return this.handleHttpResponse(() => electronAPI.api.register(phone, password, name))
  }

  async sendCode(phone: string, type: number) {
    return this.handleHttpResponse(() => electronAPI.api.sendCode(phone, type))
  }

  async loginWithCode(phone: string, code: string) {
    return this.handleHttpResponse(() => electronAPI.api.loginWithCode(phone, code))
  }

  async registerWithCode(phone: string, code: string) {
    return this.handleHttpResponse(() => electronAPI.api.registerWithCode(phone, code))
  }

  // 主页管理 API
  async getHomePages() {
    return this.handleHttpResponse(() => electronAPI.api.getHomePages())
  }

  async addHomePage(homepage: any) {
    return this.handleHttpResponse(() => electronAPI.api.addHomePage(homepage))
  }

  async updateHomePage(id: string, updates: any) {
    return this.handleHttpResponse(() => electronAPI.api.updateHomePage(id, updates))
  }

  async deleteHomePage(id: string) {
    return this.handleHttpResponse(() => electronAPI.api.deleteHomePage(id))
  }

  // 视频相关 API
  async getVideos(profileId?: string) {
    return this.handleHttpResponse(() => electronAPI.api.getVideos(profileId))
  }

  // 抖音相关 API
  async getDouyinMainPageInfo(url: string) {
    return this.handleHttpResponse(() => electronAPI.api.getDouyinMainPageInfo(url))
  }
}

/**
 * Electron服务实现类
 */
class ElectronService implements IElectronService {
  /**
   * 处理 Electron API 调用
   */
  private async handleElectronCall<T = any>(apiCall: () => Promise<T>): Promise<T> {
    try {
      return await apiCall()
    } catch (error) {
      console.error('[Electron] API call failed:', error)
      throw error
    }
  }

  // 爬取相关功能
  async startCrawl(profileId: string) {
    return this.handleElectronCall(() => electronAPI.startCrawl(profileId))
  }

  async stopCrawl(profileId: string) {
    return this.handleElectronCall(() => electronAPI.stopCrawl(profileId))
  }

  // 视频下载功能
  async downloadVideo(videoId: string) {
    return this.handleElectronCall(() => electronAPI.downloadVideo(videoId))
  }

  async cancelDownload(downloadId: string) {
    return this.handleElectronCall(() => electronAPI.cancelDownload(downloadId))
  }

  // 系统功能
  async openExternal(url: string) {
    return this.handleElectronCall(() => electronAPI.openExternal(url))
  }

  async showItemInFolder(path: string) {
    return this.handleElectronCall(() => electronAPI.showItemInFolder(path))
  }

  // 事件监听
  onCrawlProgress = (callback: (progress: any) => void) => {
    return electronAPI.onCrawlProgress(callback)
  }

  onCrawlResult = (callback: (result: any) => void) => {
    return electronAPI.onCrawlResult(callback)
  }

  onDownloadProgress = (callback: (progress: any) => void) => {
    return electronAPI.onDownloadProgress(callback)
  }

  // 认证令牌管理
  async setAuthToken(token: string | null) {
    return this.handleElectronCall(() => electronAPI.api.setAuthToken(token))
  }
}

/**
 * 统一的应用服务
 */
export class AppService implements IAppService {
  private static instance: AppService
  private apiService: ApiService
  private electronService: ElectronService

  static getInstance(): AppService {
    if (!AppService.instance) {
      AppService.instance = new AppService()
    }
    return AppService.instance
  }

  constructor() {
    this.apiService = new ApiService()
    this.electronService = new ElectronService()
  }

  // 实现所有API服务方法
  async login(phone: string, password: string) {
    return this.apiService.login(phone, password)
  }

  async register(phone: string, password: string, name?: string) {
    return this.apiService.register(phone, password, name)
  }

  async sendCode(phone: string, type: number) {
    return this.apiService.sendCode(phone, type)
  }

  async loginWithCode(phone: string, code: string) {
    return this.apiService.loginWithCode(phone, code)
  }

  async registerWithCode(phone: string, code: string) {
    return this.apiService.registerWithCode(phone, code)
  }

  async getHomePages() {
    return this.apiService.getHomePages()
  }

  async addHomePage(homepage: any) {
    return this.apiService.addHomePage(homepage)
  }

  async updateHomePage(id: string, updates: any) {
    return this.apiService.updateHomePage(id, updates)
  }

  async deleteHomePage(id: string) {
    return this.apiService.deleteHomePage(id)
  }

  async getVideos(profileId?: string) {
    return this.apiService.getVideos(profileId)
  }

  async getDouyinMainPageInfo(url: string) {
    return this.apiService.getDouyinMainPageInfo(url)
  }

  // 实现所有Electron服务方法
  async startCrawl(profileId: string) {
    return this.electronService.startCrawl(profileId)
  }

  async stopCrawl(profileId: string) {
    return this.electronService.stopCrawl(profileId)
  }

  async downloadVideo(videoId: string) {
    return this.electronService.downloadVideo(videoId)
  }

  async cancelDownload(downloadId: string) {
    return this.electronService.cancelDownload(downloadId)
  }

  async openExternal(url: string) {
    return this.electronService.openExternal(url)
  }

  async showItemInFolder(path: string) {
    return this.electronService.showItemInFolder(path)
  }

  onCrawlProgress = (callback: (progress: any) => void) => {
    return this.electronService.onCrawlProgress(callback)
  }

  onCrawlResult = (callback: (result: any) => void) => {
    return this.electronService.onCrawlResult(callback)
  }

  onDownloadProgress = (callback: (progress: any) => void) => {
    return this.electronService.onDownloadProgress(callback)
  }

  async setAuthToken(token: string | null) {
    return this.electronService.setAuthToken(token)
  }

  /**
   * 通用 HTTP 请求
   */
  async httpRequest<T = any>(config: HttpRequestConfig): Promise<HttpResponse<T>> {
    const response = await electronAPI.httpRequest<T>(config)

    // 检测401错误（未授权），表示session过期
    if (!response.success && response.status === 401) {
      console.log('[AppService] Session expired (401), clearing auth state')
      // 清除认证状态，ProtectedRoute会自动跳转到登录页
      authService.logout().catch(err => {
        console.error('[AppService] Failed to clear auth state:', err)
      })
    }

    return response
  }

  // ==================== 高级功能 ====================

  /**
   * 批量处理多个 API 调用
   */
  async batchRequest<T extends readonly unknown[]>(
    requests: { [K in keyof T]: () => Promise<T[K]> }
  ): Promise<T> {
    return Promise.all(requests.map(request => request())) as unknown as Promise<T>
  }

  /**
   * 带重试的 API 调用
   */
  async retryRequest<T>(
    apiCall: () => Promise<T>,
    maxRetries: number = 3,
    delay: number = 1000
  ): Promise<T> {
    let lastError: Error

    for (let i = 0; i < maxRetries; i++) {
      try {
        return await apiCall()
      } catch (error) {
        lastError = error as Error
        if (i < maxRetries - 1) {
          await new Promise(resolve => setTimeout(resolve, delay))
        }
      }
    }

    throw lastError!
  }
}

// ==================== 导出实例 ====================

// 导出单例实例
export const appService = AppService.getInstance()
export const authService = AuthService.getInstance()

// 为了向后兼容，保留 ipcService 别名
export const ipcService = appService

// React Hook 用于使用认证状态
export function useAuthService() {
  const [authState, setAuthState] = useState<AuthState>(authService.getAuthState())

  useEffect(() => {
    const unsubscribe = authService.subscribe(setAuthState)
    return unsubscribe
  }, [])

  return {
    ...authState,
    login: authService.login.bind(authService),
    logout: authService.logout.bind(authService),
    register: authService.register.bind(authService),
    sendVerificationCode: authService.sendVerificationCode.bind(authService),
    loginWithCode: authService.loginWithCode.bind(authService),
    registerWithCode: authService.registerWithCode.bind(authService),
    checkAuthStatus: authService.checkAuthStatus.bind(authService)
  }
}

// 导出类型
export type {
  HttpRequestConfig,
  HttpResponse,
  IAppService,
  IApiService,
  IElectronService
} from './interfaces'